<?php
namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * Summary of login(登录总结)
     * @param \Illuminate\Http\Request $request
     * @return JsonResponse
     */
    public function login(Request $request)
    {
        // 验证请求数据
        $credentials = $request->validate([
            'name' => 'required|string',
            'password' => 'required|string'
        ]);

        // 尝试使用用户名查找用户
        $user = User::where('name', $credentials['name'])->first();

        // 验证用户存在
        if(!$user) {
            return response()->json([
                'message' => '用户不存在'
            ], 401);
        }

        // 验证密码
        if(!Hash::check($credentials['password'], $user->password)){
            return response()->json([
                'message' => '密码错误'
            ], 401);
        }

        //删除旧令牌创建新令牌
        $user->tokens()->delete();
        $token = $user->createToken('blog-token', ['*'])->plainTextToken;

        // 返回响应
        return response()->json([
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'nickname' => $user->nickname,
                    'email' => $user->email,
                    'avatar' => $user->avatar ? asset($user->avatar) : null,
                ]
            ],
            'message' => '登录成功'
        ], 200);
    }

    /**
     * 获取用户信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getUserInfo(Request $request): JsonResponse
    {
        // 获取认证用户
        $user = $request->user();

        // 返回用户信息
        return response()->json([
            'data' => [
                'id' => $user->id,
                'name' => $user->name,
                'nickname' => $user->nickname,
                'email' => $user->email,
                'avatar' => $user->avatar ? asset( $user->avatar) : null,
            ],
            'message' => '获取用户信息成功',
        ], 200);
    }

    /**
     * 更新用户昵称
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function updateNickname(Request $request): JsonResponse
    {
        // 验证请求数据
        $validated = $request->validate([
            'nickname' => 'required|string|max:50',
        ]);

        $user = User::where('name', 'admin')->first();
        if(!$user) {
            return response()->json([
                'message' => '用户不存在'
            ], 401);
        }

        try {
            // 更新用户昵称
            $nickname = trim(strip_tags($validated['nickname']));
            $user->update(['nickname' => $nickname]);

            return response()->json([
                'data' => [
                    'user' => [
                        'id' => $user->id,
                        'name' => $user->name,
                        'nickname' => $user->nickname,
                        'email' => $user->email,
                        'avatar' => $user->avatar ? asset($user->avatar) : null,
                    ],
                ],
                'message' => '昵称更新成功'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => '昵称更新失败: ' . $e->getMessage(),
            ], 500);
        }
    }
    
    /**
     * 注销用户并删除令牌
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function logout(Request $request): JsonResponse
    {
        // 删除当前用户token
        try{
            $request->user()->currentAccessToken()->delete();

            return response()->json([
                'message' => '退出登录成功'
            ], 200);
        } catch (\Exception $e){
            return response()->json([
                'message' => '退出登录失败'. $e->getMessage()
            ], 500);
        }
    }
}